import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class ShareDataWidget extends InheritedWidget {
  final int data;

  static ShareDataWidget of(BuildContext context) {
    return context.getElementForInheritedWidgetOfExactType<ShareDataWidget>().widget;
  }

  @override
  bool updateShouldNotify(ShareDataWidget oldWidget) {
    // TODO: implement updateShouldNotify
    return oldWidget.data != data;
  }

  ShareDataWidget({@required this.data, Widget child}) : super(child: child);
}

class TestWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _TestWidgetState();
  }
}

class _TestWidgetState extends State<TestWidget> {
  BuildContext context;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    this.context = context;
    return Text(ShareDataWidget
        .of(context)
        .data
        .toString());
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    if (context != null) {
      Fluttertoast.showToast(msg: ShareDataWidget
          .of(context)
          .data
          .toString());
    }
  }

}

class InheritedWidgetTest extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _InheritedWidgetState();
  }
}

class _InheritedWidgetState extends State<InheritedWidgetTest> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('Inherited'),
      ),
      body: Center(
        child: ShareDataWidget(
          data: _count,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TestWidget(),
              OutlineButton(
                child: Text("+1"),
                onPressed: () {
                  setState(() {
                    _count++;
                  });
                },
              )
            ],
          ),
        ),
      ),
    );
  }

}